package top.v5it.japi.plus.core.spring.web;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import top.v5it.japi.plus.core.ConstantPool;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


/**
 * 拦截防止xss注入
 * 通过Jsoup过滤请求参数内的特定字符
 *
 * @author zhanpu
 */
@Slf4j
public class JapiXssFilter implements Filter {

    /**
     * 初始化参数名称 isIncludeRichText
     */
    public final static String INIT_PARAMETER_NAME_IS_INCLUDE_RICH_TEXT = "isIncludeRichText";

    /**
     * 初始化参数名称 excludes
     */
    public final static String INIT_PARAMETER_NAME_EXCLUDES = "excludes";

    /**
     * 排除过虑的请求地址
     */
    private static List<Pattern> excludes;

    /**
     * 是否过滤富文本内容
     */
    private static boolean isIncludeRichText = false;

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        log.debug("+++++xss filter is open+++++");
        HttpServletRequest req = (HttpServletRequest) request;

        if (handleExcludeURL(req.getServletPath())) {
            filterChain.doFilter(request, response);
            return;
        }

        filterChain.doFilter(new JapiXssHttpServletRequestWrapper(req, isIncludeRichText), response);
    }

    /**
     * 排除不做xss地址
     *
     * @param request
     * @param response
     * @return
     */
    private boolean handleExcludeURL(final String servletPath) {
        return CollUtil.isNotEmpty(excludes)
                && StrUtil.isNotBlank(servletPath)
                && excludes.stream().anyMatch(v -> v.matcher(servletPath).find());
    }

    /**
     * 初始化过虑器参数
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("+++++xss filter init ...+++++");

        String tempIsIncludeRichText = filterConfig.getInitParameter(INIT_PARAMETER_NAME_IS_INCLUDE_RICH_TEXT);
        isIncludeRichText =
                Optional.ofNullable(tempIsIncludeRichText)
                        .map(Boolean::parseBoolean)
                        .orElse(Boolean.FALSE);

        String excludeStr = filterConfig.getInitParameter(INIT_PARAMETER_NAME_EXCLUDES);
        List<String> excludeList =
                Optional.ofNullable(excludeStr)
                        .map(v -> StrUtil.splitTrim(v, ConstantPool.COMMA))
                        .orElse(Collections.emptyList());

        excludes =
                excludeList.stream()
                        .map(v -> Pattern.compile("^" + v))
                        .collect(Collectors.toList());
    }

    @Override
    public void destroy() {
        if (CollUtil.isNotEmpty(excludes)) {
            excludes.clear();
            excludes = null;
        }
    }
}
